package com.qili.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.entity.BasePathConfig;
import com.qili.base.entity.CurrentUser;
import com.qili.base.service.BasePathConfigService;
import com.qili.core.annotation.Log;
import com.qili.core.shiro.Principal;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseDict;
import com.qili.entity.exam.*;
import com.qili.entity.exam.dto.ExExamDTO;
import com.qili.entity.supervisor.ProjectNotice;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.dto.SupervisorProjectDTO;
import com.qili.entity.sys.SysLog;
import com.qili.entity.sys.SysRole;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.exception.MyException;
import com.qili.mapper.BasePathConfigMapper;
import com.qili.mapper.exam.ExPaperMapper;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.mapper.sys.SysUserMapper;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.exam.*;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.service.sys.RoleService;
import com.qili.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static java.util.Objects.isNull;

/**
 * @author zhangxiaopeng
 * @date 2021-08-16
 * @description考试管理
 */
@Slf4j
@Controller
@RequestMapping("/exam/list")
public class ExamListController {

    @Autowired
    ExExamService exExamService;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserService userService;
    @Autowired
    ExStuExamService exStuExamService;
    @Autowired
    ExExamPaperService exExamPaperService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    BaseCompanyService companyService;
    @Autowired
    RoleService roleService;
    @Autowired
    UploadUtil uploadUtil;
    @Autowired
    SupervisorFileService supervisorFileService;
    @Autowired
    ExPaperService exPaperService;
    @Autowired
    ExPaperMapper expaperMapper;
    @Autowired
    BasePathConfigService basePathConfigService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    SysLogMapper sysLogMapper;
    @Autowired
    ExStuExamDetailService exStuExamDetailService;

    /**
     * @param model
     * @Description:考试列表跳转
     * @Date:14:58 2021-08-16
     */
    @RequestMapping("/index")
    @RequiresPermissions("zh:kslb")
    public String index(Model model) {
        //考试模式
        List<BaseDict> stnd = baseDictService.selectByTypeCode(DictTypes.KSMS.getType());
        model.addAttribute("ksms", stnd);
        return "/examList/examIndex";
    }

    /**
     * @param model
     * @Description:考试新增页面跳转
     * @Date:15:01 2021-08-16
     */
    @RequestMapping("/examadd")
    public String examAdd(Model model, String examId) {
        if (StringUtils.isNotBlank(examId)) {
            model.addAttribute("examId", examId);
        }
        SupervisorFile supervisorFile = new SupervisorFile();
        supervisorFile.setProjectId(examId);
        supervisorFile.setType("0819");
        SupervisorFile file = supervisorFileService.selectOne(supervisorFile);
        if (file != null) {
            file.setUrl(url(file.getUrl()));
            model.addAttribute("file", file);
        }
        //考试模式
        List<BaseDict> stnd = baseDictService.selectByTypeCode(DictTypes.KSMS.getType());
        model.addAttribute("ksms", stnd);
        //考试分类
        List<BaseDict> ksfl = baseDictService.selectByTypeCode(DictTypes.KSFL.getType());
        model.addAttribute("ksfl", ksfl);
        return "/examList/examAdd";
    }


    //创建时提前生成ID
    @GetMapping("/examId")
    @ResponseBody
    public JsonUtil examId() {
        JsonUtil json = new JsonUtil();
        json.setData(IdUtil.simpleUUID());
        json.setFlag(true);
        return json;
    }

    /**
     * @param model
     * @param examId
     * @Description:修改页面跳转
     * @Date:17:39 2021-08-19
     */
    @GetMapping("/examUpdate")
    public String examUpdate(Model model, String examId) {
        ExExam exam = exExamService.selectByPrimaryKey(examId);
        //上传的封面
        SupervisorFile supervisorFile = new SupervisorFile();
        supervisorFile.setProjectId(examId);
        supervisorFile.setType("0819");
        SupervisorFile file = supervisorFileService.selectOne(supervisorFile);
        if (file != null) {
            file.setUrl(url(file.getUrl()));
            model.addAttribute("file", file);
        }
        //考试模式
        List<BaseDict> stnd = baseDictService.selectByTypeCode(DictTypes.KSMS.getType());
        model.addAttribute("ksms", stnd);
        //考试分类
        List<BaseDict> ksfl = baseDictService.selectByTypeCode(DictTypes.KSFL.getType());
        model.addAttribute("ksfl", ksfl);
        model.addAttribute("ex", exam);

        return "/examList/examUpdate";
    }

    //图片的url
    public String url(String url) {
        String imgUrl = url;
        String uploadPath = uploadUtil.getUploadPath();
        imgUrl = imgUrl.substring(uploadPath.length());
        imgUrl = File.separator + "itfile" + File.separator + imgUrl;
        return imgUrl;
    }

    /**
     * @param
     * @Description:回收页面跳转
     * @Date:15:38 2021-08-23
     */
    @GetMapping("/recycleBin")
    public String recycleBin() {
        return "/examList/recycleBin";
    }

    /**
     * @param model
     * @Description:试卷新增页面跳转
     * @Date:15:01 2021-08-16
     */
    @RequestMapping("/exPaper")
    public String exPaper(Model model, String examId) {
        model.addAttribute("examId", examId);
        return "/examList/exPaper";
    }

    /**
     * @param model
     * @Description:考生新增页面跳转
     * @Date:15:01 2021-08-16
     */
    @RequestMapping("/exUser")
    public String exUser(Model model, String examId) {
        //部门
        BaseDict deptDict = new BaseDict();
        deptDict.setBadtTypecode(DictTypes.DEPT.getType());
        List<BaseDict> deptList = baseDictService.select(deptDict);
        model.addAttribute("deptList", deptList);
        //公司
        Example example = new Example(BaseCompany.class);
        List<BaseCompany> companyList = companyService.selectByExample(example);
        model.addAttribute("companyList", companyList);
        //角色
        List<SysRole> sysRoles = roleService.selectAll();
        model.addAttribute("js", sysRoles);

        model.addAttribute("examId", examId);
        return "/examList/exUser";
    }


    /**
     * @param exam
     * @param page
     * @param limit
     * @Description:查询考试
     * @Date:17:31 2021-08-17
     */
    @GetMapping("/selectExam")
    @ResponseBody
    public ReType selectExam(ExExamDTO exam, int page, int limit) {
        List<ExExamDTO> examList = new ArrayList<>();
        Page<ExExamDTO> tPage = PageHelper.startPage(page, limit);
        try {
            examList = exExamService.selectExam(exam);
            //获取封面的url
            if (examList != null && examList.size() > 0) {
                for (int i = 0; i < examList.size(); i++) {
                    SupervisorFile supervisorFile = new SupervisorFile();
                    supervisorFile.setProjectId(examList.get(i).getExamId());
                    supervisorFile.setType("0819");
                    SupervisorFile file = supervisorFileService.selectOne(supervisorFile);
                    if (file != null) {
                        examList.get(i).setUrl(url(file.getUrl()));
                    }
                }
            }
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), examList);
    }

    /**
     * @param exam
     * @param page
     * @param limit
     * @Description:考试系统回收站列表查询
     * @Date:15:42 2021-08-23
     */
    @GetMapping("selectKs")
    @ResponseBody
    public ReType selectKs(ExExamDTO exam, int page, int limit) {
        List<ExExamDTO> ksList = null;
        Page<ExExamDTO> tPage = PageHelper.startPage(page, limit);
        try {
            ksList = exExamService.selectExam(exam);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), ksList);
    }

    /**
     * @param
     * @Description:回收站彻底删除
     * @Date:16:19 2021-08-23
     */
    @GetMapping("deleteKs")
    @ResponseBody
    public JsonUtil deleteKs() {
        JsonUtil json = new JsonUtil();
        try {
            ExExam ex = new ExExam();
            ex.setStatus("000");
            //if (exExamService.delete(ex) > 0) {
            List<ExExam> select = exExamService.select(ex);
            deleteAll(select);
            json.setFlag(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("删除失败");
        }
        return json;
    }

    public void deleteAll(List<ExExam> select) {
        if (select != null) {
            if (select.size() > 0) {
                for (int i = 0; i < select.size(); i++) {
                    ExExam exam = select.get(i);
                    SysLog sysLog = new SysLog();
                    sysLog.setCreateTime(new Date());
                    sysLog.setType("DEL");
                    sysLog.setText("从回收站中删除考试");
                    sysLog.setParam("参数：" + exam.getExamName());
                    sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
                    CurrentUser currentUser = Principal.getCurrentUse();
                    sysLog.setUserName(currentUser.getUsername());
                    sysLogMapper.insert(sysLog);
                    exExamService.delete(exam);
                }
            }
        }
    }

    /**
     * @param
     * @Description:回收站删除
     * @Date:15:45 2021-10-22
     */
    @GetMapping(value = "/delFromRecycle")
    @ResponseBody
    public JsonUtil delFromRecycle(String examId) {
        try {
            if (StringUtil.isBlank(examId)) {
                return JsonUtil.error("参数有误");
            }
            ExExam exam = exExamService.selectByPrimaryKey(examId);

            int count = exExamService.delFromRecycle(examId);
            if (count <= 0) {
                return JsonUtil.error("删除失败");
            }
            insertFileLog("从回收站删除考试","参数："+exam.getExamName(),"DEL");
            return JsonUtil.sucess("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("删除失败" + e.getMessage());
        }

    }

    /**
     * @param
     * @Description:回收站批量删除
     * @Date:15:45 2021-10-22
     */
    @PostMapping(value = "deleteFromRecycle")
    @ResponseBody
    public JsonUtil deleteFromRecycle(@RequestBody String[] ids) {
        try {
            if (ids == null || ids.length < 0) {
                return JsonUtil.error("参数有误");
            }
            for (String id : ids) {
                ExExam exam = exExamService.selectByPrimaryKey(id);
                insertFileLog("从回收站删除考试","参数："+exam.getExamName(),"DEL");
            }
            int count = exExamService.deleteFromRecycle(ids);
            if (count <= 0) {
                return JsonUtil.error("删除失败");
            }
            return JsonUtil.sucess("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("删除失败" + e.getMessage());
        }
    }


    /**
     * @param
     * @Description:回收站批量还原
     * @Date:15:45 2021-10-22
     */
    @PostMapping(value = "hyAll")
    @ResponseBody
    public JsonUtil hyAll(@RequestBody String[] ids) {
        try {
            if (ids == null || ids.length < 0) {
                return JsonUtil.error("参数有误");
            }
            int count = exExamService.hyAll(ids);
            if (count > 0) {
                return JsonUtil.sucess("还原成功");
            }
            return JsonUtil.error("还原失败");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("还原失败" + e.getMessage());
        }
    }

        /**
         * @param exam
         * @Description:考试新增
         * @Date:15:45 2021-08-17
         */
        @PostMapping("/insertExam")
        @ResponseBody
        @RequiresRoles("ksgly")
        public JsonUtil insertExam (ExExam exam){
            JsonUtil json = new JsonUtil();
            try {
                insertFileLog("新增考试","参数："+exam.getExamName(),"ADD");
                exam.setCreateBy(CommonUtil.getUserId());
                exam.setCreateDate(DateUtil.getCurrentDateString());
                if (exExamService.insert(exam) > 0) {
                    if ("002".equals(exam.getStatus())) {
                        sendNoticeCheckToAdmin(exam.getExamId());
                    }
                    json.setFlag(true);
                    return json;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            json.setFlag(false);
            return json;
        }

        /**
         * @param exam
         * @Description:编辑考试
         * @Date:15:45 2021-08-17
         */
        @PostMapping("/updateExam")
        @ResponseBody
        @RequiresRoles("ksgly")
        public JsonUtil updateExam (ExExam exam){
            JsonUtil json = new JsonUtil();
            try {
                insertFileLog("更新考试","参数："+exam.getExamName(),"UPDATE");
                exam.setModifyBy(CommonUtil.getUserId());
                exam.setModifyDate(DateUtil.getCurrentDateString());
                if (exExamService.updateByPrimaryKeySelective(exam) > 0) {
                    if ("002".equals(exam.getStatus())) {
                        sendNoticeCheckToAdmin(exam.getExamId());
                    }
                    json.setFlag(true);
                    return json;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            json.setFlag(false);
            return json;
        }


        /**
         * @param ids
         * @param status
         * @Description:批量修改数据
         * @Date:14:51 2021-08-23
         */
        @GetMapping("/updateExams")
        @ResponseBody
        @RequiresRoles("ksgly")
        public JsonUtil updateExams (String[]ids, String status){
            JsonUtil json = new JsonUtil();
            //如果修改类型为已提交 先判断这个考试有无试卷
            if ("002".equals(status)) {
                for (String id : ids) {
                    ExExamPaper exExamPaper = new ExExamPaper();
                    exExamPaper.setExamId(id);
                    int paperCount = exExamPaperService.selectCount(exExamPaper);
                    if (paperCount <= 0) {
                        json.setFlag(false);
                        json.setMsg("所选行包含未选择试卷的考试");
                        return json;
                    }
                }
            }
            Map map = new HashMap();
            try {
                if (ids != null && ids.length > 0) {
                    map.put("ids", ids);
                    map.put("status", status);
                    map.put("modifyBy", CommonUtil.getUserId());
                    map.put("modifyDate", DateUtil.getCurrentDateString());
                    exExamService.updateExam(map);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            json.setFlag(true);
            json.setMsg("请求失败");
            return json;
        }

        public void sendNoticeCheckToAdmin (String id){
            ExExam exam = exExamService.selectByPrimaryKey(id);
            ExStuExam exStuExam = new ExStuExam();
            exStuExam.setExamId(id);
            List<ExStuExam> list = exStuExamService.select(exStuExam);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    ProjectNotice notice = new ProjectNotice();
                    notice.setLinkId(list.get(i).getUserId());
                    notice.setIsView("0");
                    notice.setSendTo(list.get(i).getUserId());
                    notice.setTitle("考试" + exam.getExamName() + "已发布,有时间请去考试");
                    notice.setNoticeType("114");//通知类型 账号通知 001  002 流程进展通知
                    notice.setApplicantType("005");// 考试
                    projectNoticeServie.insertSelective(notice);
                }
            }
        }

    /**
     * 已提交的考试，新增人员时，给新增人员发送短信通知
     * @param examId
     * @param userId
     */
    public void sendNoticeCheckToAdminAdd (String examId,String userId){
            ExExam exam = exExamService.selectByPrimaryKey(examId);
            ProjectNotice notice = new ProjectNotice();
            notice.setLinkId(userId);
            notice.setIsView("0");
            notice.setSendTo(userId);
            notice.setTitle("考试" + exam.getExamName() + "已发布,有时间请去考试");
            notice.setNoticeType("114");//通知类型 账号通知 001  002 流程进展通知
            notice.setApplicantType("005");// 考试
            projectNoticeServie.insertSelective(notice);

        }

        /**
         * @param user
         * @param page
         * @param limit
         * @Description:查询可以添加的人员
         * @Date:9:22 2021-08-18
         */
        @GetMapping("/selectUser")
        @ResponseBody
        public ReType selectUser (SysUserDTO user,int page, int limit, ExStuExam exam){
            //查询已选中的考生
            List<ExStuExam> exStu = exStuExamService.select(exam);
            List<SysUserDTO> userList = new ArrayList<>();
            Page<SysUserDTO> tPage = PageHelper.startPage(page, limit);
            List<String> ids = new ArrayList<>();
            for (int i = 0; i < exStu.size(); i++) {
                ids.add(exStu.get(i).getUserId());
            }
            Map map = new HashMap();
            //去掉已选中的考生
            map.put("notIds", ids);
            map.put("realName", user.getRealName());
            map.put("companyId", user.getCompanyName());
            map.put("deptId", user.getDeptName());
            map.put("roleId", user.getRoleId());
            try {
                userList = sysUserMapper.selectExstu(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new ReType(tPage.getTotal(), userList);
        }

        /**
         * @param ids
         * @param exam
         * @Description:添加考生
         * @Date:11:59 2021-08-18
         */
        @GetMapping("/insertExStuExam")
        @ResponseBody
        public JsonUtil insertExStuExam (String ids, ExStuExam exam){
            List<String> userIdList = new ArrayList<>();
            JsonUtil json = new JsonUtil();
            String[] arr = ids.split(",");
            try {
                for (int i = 0; i < arr.length; i++) {
                    exam.setStuExamId(IdUtil.simpleUUID());
                    exam.setUserId(arr[i]);
                    exam.setCreateBy(CommonUtil.getUserId());
                    exam.setCreateDate(DateUtil.getCurrentDateString());
                    // 2022年3月28日17:20:57 判断是否存在当前的人，存在提示
                    ExStuExam ex = new ExStuExam();
                    ex.setExamId(exam.getExamId());
                    ex.setUserId(exam.getUserId());
                    List<ExStuExam> select = exStuExamService.select(ex);
                    if (null != select && select.size() > 0){
                        // 存在，不插入
                        userIdList.add(exam.getUserId());
                    }else {
                        exStuExamService.insert(exam);
                    }
                    if("002".equals(exam.getState())){
                        // 插入之后，给新加的人发送考试提醒
                        sendNoticeCheckToAdminAdd(exam.getExamId(),arr[i]);
                    }
                }
                // 判断 userIdList 是否为空
                if (userIdList != null && userIdList.size() > 0){
                    List<SysUser> sysUsers = new ArrayList<>();
                    for (String userId : userIdList) {
                        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
                        if (null != sysUser){
                            sysUsers.add(sysUser);
                        }
                    }
                    if (sysUsers != null && sysUsers.size() > 0){
                        // 弄个状态码，标识存在此用户
                        json.setStatus(601);
                        json.setData(sysUsers);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            json.setFlag(true);
            return json;
        }

        /**
         * @param exam
         * @param page
         * @param limit
         * @Description:查询考生
         * @Date:13:16 2021-08-18
         */
        @GetMapping("/selectExStuExam")
        @ResponseBody
        public ReType selectExStuExam (ExStuExam exam,int page, int limit){
            //根据考试id查询对应考生
            List<ExStuExam> userList = exStuExamService.select(exam);
            List<String> ids = new ArrayList<>();
            for (int i = 0; i < userList.size(); i++) {
                ids.add(userList.get(i).getUserId());
            }
            List<SysUserDTO> sysUser = new ArrayList<>();
            Page<SysUserDTO> tPage = PageHelper.startPage(page, limit);
            Map map = new HashMap();
            map.put("ids", ids);
            try {
                if (ids != null && ids.size() > 0) {
                    sysUser = sysUserMapper.selectExstu(map);
                    //查看该考生是否已考试
                    // 2021年11月12日10:14:33 修改查询考试明细表-判断是否考试
                    if (sysUser != null && sysUser.size() > 0) {
                        for (int j = 0; j < sysUser.size(); j++) {
                            Example example = new Example(ExStuExamDetail.class);
                            Example.Criteria criteria = example.createCriteria();
                            criteria.andEqualTo("examId", exam.getExamId());
                            criteria.andEqualTo("userId", sysUser.get(j).getId());
//                        criteria.andEqualTo("state", "002");
                            List<ExStuExamDetail> stu = exStuExamDetailService.selectByExample(example);
                            if (stu != null && stu.size() > 0) {
                                sysUser.get(j).setValue("是");
                            } else {
                                sysUser.get(j).setValue("否");
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new ReType(tPage.getTotal(), sysUser);
        }

        /**
         * @param exam
         * @Description:删除考生
         * @Date:17:05 2021-08-18
         */
        @GetMapping("/deleteExStu")
        @ResponseBody
        @Log(desc = "从考试列表中删除考生", type = Log.LOG_TYPE.DEL)
        public JsonUtil deleteExStu (ExStuExam exam){
            JsonUtil json = new JsonUtil();
            if (StringUtils.isNotBlank(exam.getUserId())) {
                if (exStuExamService.delete(exam) > 0) {
                    json.setFlag(true);
                    return json;
                }
            }
            json.setFlag(false);
            return json;
        }

        /**
         * @param filedata
         * @param dto
         * @Description:上传封面
         * @Date:11:41 2021-08-19
         */
        @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
        @ResponseBody
        public JsonUtil addFile (@RequestParam(value = "file", required = false) MultipartFile
        filedata, SupervisorProjectDTO dto){
            // 当前用户信息
            String AsUserId = "";
            if (StringUtils.isBlank(dto.getUserId())) {
                AsUserId = CommonUtil.getUserId();
            }
            if (StringUtils.isBlank(AsUserId)) {
                return JsonUtil.error("获取用户信息出错");
            }
            SysUser sysUser = userService.selectByPrimaryKey(AsUserId);
            String AsType = dto.getType();

            JsonUtil re = new JsonUtil();
            try {
                //判断用户是否有创建好的文件夹,如果有创建好的文件夹,新方式存储,如果没有创建好的文件夹,老方式存储:
                LoadType userLoadType = new LoadType();
                if (StringUtils.isBlank(sysUser.getInfoDic())) {
                    //创建用户目录：
                    userService.setUserFilePath(sysUser);
                }
                userLoadType = getLoadTypeByUser("0819", sysUser, filedata);

                //保存文件
                FileUtils.copyInputStreamToFile(filedata.getInputStream(), userLoadType.getCurrentFile());
                //保存文件表
                SupervisorFile AoPostSf = new SupervisorFile();
                //用户id
                AoPostSf.setProjectId(dto.getProjectId());
                //文件类型
                AoPostSf.setType(AsType);

                SupervisorFile supervisorFile = supervisorFileService.selectOne(AoPostSf);
                AoPostSf.setFileName(userLoadType.getFileName());
                AoPostSf.setFileType(userLoadType.getSuffix());
                AoPostSf.setType(dto.getType());
                AoPostSf.setCreateBy(AsUserId);
                AoPostSf.setCreateDate(new Date());
                String fileUrl = "";
                //设置AoPostSf的url 为文件的全路径
                AoPostSf.setUrl(userLoadType.getCurrentFile().getPath());
                //增加/更改supervisor_file表
                if (isNull(supervisorFile)) {
                    supervisorFileService.insert(AoPostSf);
                    supervisorFileService.setFilePathDics(AoPostSf);
                } else {
                    AoPostSf.setId(supervisorFile.getId());
                    if ("552".equals(AsType) && "2".equals(supervisorFile.getLcStatus())) {
                        re.setStatus(Integer.valueOf(supervisorFile.getLcStatus()));
                    }
                    supervisorFileService.updateByPrimaryKey(AoPostSf);
                }
                //返回值data带着图片的路径
                //前半截:   截取掉uploadPath    如果是以 userPath开头  则为 /userfile    如果是以 personalPath开头则为 /images
                //后半截:    如果用户的info_dic为空  则为图片名称     如果用户的info_dic不为空  则为用户的info_dic+图片名称
                re.setData(fileUrl);
                if ("202".equals(AsType) || "203".equals(AsType)) {
                    //处理图片背景透明度
                    ImageUtil.transparentBackground(userLoadType.getCurrentFile().getPath(), "png", userLoadType.getCurrentFile().getPath());
                }
            } catch (Exception e) {
                re.setMsg(e.getMessage());
                re.setFlag(false);
                e.printStackTrace();
            }
            return re;
        }


        /**
         * 根据用户获取loadType
         *
         * @param user
         * @return
         */
        @SneakyThrows
        private LoadType getLoadTypeByUser (String fileType, SysUser user, MultipartFile file){
            if (user == null || file == null || user == null) {
                return null;
            }
            LoadType loadType = new LoadType();
            if (uploadUtil.whehterAllowFileType(file)) {
                //获取文件名称: 把文件原名称  文件后缀   文件新名称存入loadType
                formatUserFileNameByFileType(fileType, file, loadType, user);
                //准备好文件所在文件夹,判断有没有文件,有的话删除原文件,并创建新文件
                getCurrentFilePath(loadType, user);
            } else {
                throw new MyException("抱歉，上传文件不是允许的文件类型！！");
            }
            return loadType;
        }

        /**
         * 编辑真实存储路径
         *
         * @param loadType
         * @param user
         * @throws IOException
         */
        private void getCurrentFilePath (LoadType loadType, SysUser user) throws IOException {
            StringBuffer filePath = new StringBuffer();
            //拼接新文件的全路径
            BasePathConfig basePathConfig = new BasePathConfig();
            basePathConfig.setBfcId("0819");
            BasePathConfig base = basePathConfigService.selectOne(basePathConfig);
            if (base != null && StringUtil.isNotBlank(base.getBfcTemplateFile())) {
                String currentFileFullName = base.getBfcTemplateFile();
                filePath.append(uploadUtil.getUploadPath()).append(currentFileFullName).append(File.separator);
            } else {
                filePath.append(uploadUtil.getUploadPath()).append(uploadUtil.getPersonPath()).append(File.separator);
            }
            File fileDic = new File(filePath.append(loadType.getFileName()).toString());
            File f = fileDic.getParentFile();
            //如果目录不存在,创建目录
            if (!f.exists() || f.isFile()) {
                f.mkdirs();
            }
            File file = new File(FilePathUtil.doFileSeparator(filePath.append(loadType.getFileName()).toString()));
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            loadType.setCurrentFile(file);
        }

        private void formatUserFileNameByFileType (String fileType, MultipartFile file, LoadType loadType, SysUser user)
        {
            //文件原名称
            String fileFuleName = file.getOriginalFilename();
            //文件后缀   .xxx
            String fileSuffix = fileFuleName.substring(fileFuleName.lastIndexOf("."));
            //获取文件类型对应的文件名称
            String fileNameFront = uploadUtil.getUserFileName(fileType);
            //如果没有指定目录,文件名称带上用户名前缀
            if (StringUtils.isBlank(user.getInfoDic())) {
                fileNameFront = user.getRealName() + "_" + fileNameFront;
            }
            //拼接新的文件名称
            String fileName = fileNameFront + DateUtil.getCurrentDateTimeStringNoSpliter() + fileSuffix;
            loadType.setOriginalFileName(fileFuleName);
            loadType.setFileName(fileName);
            loadType.setSuffix(fileSuffix);
        }


        /**
         * @param exPaper
         * @param page
         * @param limit
         * @param exam
         * @Description:查询可选的试卷
         * @Date:14:09 2021-08-19
         */
        @GetMapping("/selectExPaper")
        @ResponseBody
        public ReType selectExPaper (ExPaper exPaper,int page, int limit, ExExamPaper exam){
            //查询已选中的试卷
            List<ExExamPaper> examPaper = exExamPaperService.select(exam);
            List<ExPaper> paper = new ArrayList<>();
            Page<ExPaper> tPage = PageHelper.startPage(page, limit);
            List<String> ids = new ArrayList<>();
            for (int i = 0; i < examPaper.size(); i++) {
                ids.add(examPaper.get(i).getPaperId());
            }
            Map map = new HashMap();
            //去掉已选中的试卷
            map.put("notIds", ids);
            map.put("paperName", exPaper.getPaperName());
            try {
                paper = expaperMapper.selectExPaper(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new ReType(tPage.getTotal(), paper);
        }

        /**
         * @param ids
         * @param exam
         * @Description:添加试卷
         * @Date:11:59 2021-08-19
         */
        @GetMapping("/insertExExamPaper")
        @ResponseBody
        public JsonUtil insertExExamPaper (String ids, ExExamPaper exam){
            JsonUtil json = new JsonUtil();
            String[] arr = ids.split(",");
            try {
                for (int i = 0; i < arr.length; i++) {
                    exam.setExamPaperId(IdUtil.simpleUUID());
                    exam.setPaperId(arr[i]);
                    exam.setCreateBy(CommonUtil.getUserId());
                    exam.setCreateDate(DateUtil.getCurrentDateString());
                    exExamPaperService.insert(exam);
                           }
            } catch (Exception e) {
                e.printStackTrace();
            }
            json.setFlag(true);
            return json;
        }

        //日志
        public void insertFileLog(String text,String param,String type ) {
            SysLog sysLog = new SysLog();
            sysLog.setCreateTime(new Date());
            sysLog.setType(type);
            sysLog.setText(text);
            sysLog.setParam(param);
            sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
            CurrentUser currentUser = Principal.getCurrentUse();
            sysLog.setUserName(currentUser.getUsername());
            sysLogMapper.insert(sysLog);
        }

        /**
         * @param exam
         * @param page
         * @param limit
         * @Description:查询添加的试卷
         * @Date:13:16 2021-08-18
         */
        @GetMapping("/selectExExamPaper")
        @ResponseBody
        public ReType selectExExamPaper (ExExamPaper exam,int page, int limit){
            //查询已选中的试卷
            List<ExExamPaper> examPaper = exExamPaperService.select(exam);
            List<ExPaper> paper = new ArrayList<>();
            Page<ExPaper> tPage = PageHelper.startPage(page, limit);
            List<String> ids = new ArrayList<>();
            for (int i = 0; i < examPaper.size(); i++) {
                ids.add(examPaper.get(i).getPaperId());
            }
            Map map = new HashMap();
            //去掉已选中的试卷
            map.put("ids", ids);
            try {
                if (ids != null && ids.size() > 0) {
                    paper = expaperMapper.selectExPaper(map);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new ReType(tPage.getTotal(), paper);
        }

        /**
         * @param exam
         * @Description:删除试卷
         * @Date:17:05 2021-08-19
         */
        @GetMapping("/deleteExPaper")
        @ResponseBody
        @Log(desc = "从考试列表中删除试卷", type = Log.LOG_TYPE.DEL)
        public JsonUtil deleteExPaper (ExExamPaper exam){
            JsonUtil json = new JsonUtil();
            if (StringUtils.isNotBlank(exam.getPaperId())) {
                if (exExamPaperService.delete(exam) > 0) {
                    json.setFlag(true);
                    return json;
                }
            }
            json.setFlag(false);
            return json;
        }

        /**
         * @param request
         * @param response
         * @param dto
         * @Description:导出
         * @Date:16:11 2021-09-10
         */
        @GetMapping("/exportKs")
        @RequiresRoles("ksgly")
        public void exportKs (HttpServletRequest request, HttpServletResponse response, ExExamDTO dto){
            String fileName = "考试列表" + DateUtil.getCurrentDateNoSpliter();
            HashMap map = new HashMap();
            //选中的考试数据
            List<ExExamDTO> examList = exExamService.selectExam(dto);
            //题目
            map.put("name", "考试列表");
            map.put("examLists", examList);
            try {
                ExcelExportUtilEX.exportExcel(response, map, fileName, "KS002");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
